<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Wilead\ApiBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View AS FOSView;

/**
 * Description of ApiController
 *
 * @author jack
 */
class ApiController extends Controller {

    /**
     * @return \FOS\RestBundle\View\View
     */
    public function getFOSView() {
        return FOSView::create();
    }

    /**
     * @param object $entity
     * @return array
     */
    public function validatorEntity($entity) {
        $validator = $this->getValidator();
        return $validator->validate($entity);
    }

    /**
     * @return \Symfony\Component\Validator\Validator
     */
    public function getValidator() {
        return $this->get('validator');
    }

    /**
     * Get the validation errors
     * @param \Symfony\Component\Validator\ConstraintViolationList $errors Validator error list
     * @return \FOS\RestBundle\View\View
     */
    public function getErrorsView($errors) {
        $msgs = array();
        $it = $errors->getIterator();
        //$val = new \Symfony\Component\Validator\ConstraintViolation();
        foreach ($it as $val) {
            $msg = $val->getMessage();
            $params = $val->getMessageParameters();
            //using FOSUserBundle translator domain 'validators'
            $msgs[$val->getPropertyPath()][] = $this->get('translator')->trans($msg, $params, 'validators');
        }
        $view = FOSView::create($msgs);
        $view->setStatusCode(400);
        return $view;
    }

    public function insertIntoEntity($request, $entity, $fields = array()) {
        foreach ($fields as $field) {
            $method = 'set' . ucfirst($field);
            if ($request->has($field)) {
                $entity->$method($request->get($field));
            }
        }

        return $entity;
    }

    /**
     * @return \Doctrine\ORM\EntityManager
     */
    public function getEntityManager() {
        return $this->getDoctrine()->getManager();
    }

    /**
     * 创建删除表单
     * @param type $id
     */
    public function createDeleteForm($id = NULL) {
        return $this->createFormBuilder()
                        ->add('id')
                        ->getForm();
    }

    public function getRepository($repository) {
        return $this->getEntityManager()->getRepository($repository);
    }

}

?>
